package config

import (
	"common/helper"
	"database/sql"
	"math/rand"
	"sync"
	"time"
)

const (
	TurnTable_Silver  = 1
	TurnTable_Gold    = 2
	TurnTable_Diamond = 3
)

type CfgTurnTableItem struct {
	Id         int     `json:"id" db:"id" cbor:"id"`
	Type       int     `json:"type" db:"type" cbor:"type"`
	LuckyPoint float64 `json:"lucky_point" db:"lucky_point" cbor:"lucky_point"`
	Rate       int     `json:"rate" db:"rate" cbor:"rate"`
}

var HcmTurnTableListCfg sync.Mutex
var G_CfgTurnTableList []CfgTurnTableItem

func AddTurnTableSetRow(rows *sql.Rows) {
	var tVal CfgTurnTableItem
	var err error
	err = rows.Scan(&tVal.Id, &tVal.Type, &tVal.LuckyPoint, &tVal.Rate)

	if err != nil {
		helper.InfoLog("AddTurnTableSetRow scan err")
		return
	}

	HcmTurnTableListCfg.Lock()
	defer HcmTurnTableListCfg.Unlock()

	G_CfgTurnTableList = append(G_CfgTurnTableList, tVal)
}

func TurnTableSetRowRemove() {
	HcmTurnTableListCfg.Lock()
	defer HcmTurnTableListCfg.Unlock()
	G_CfgTurnTableList = []CfgTurnTableItem{}
}

type CfgTClientItem struct {
	Id         int     `json:"id" db:"id" cbor:"id"`
	LuckyPoint float64 `json:"lucky_point" db:"lucky_point" cbor:"lucky_point"`
}

func GetTurnTableCfg(turnTableType int) []CfgTClientItem {
	HcmTurnTableListCfg.Lock()
	defer HcmTurnTableListCfg.Unlock()

	var CfgTurnTableList []CfgTClientItem

	for _, cfgItem := range G_CfgTurnTableList {
		if cfgItem.Type == turnTableType {
			var clItem CfgTClientItem
			clItem.Id = cfgItem.Id
			clItem.LuckyPoint = cfgItem.LuckyPoint
			CfgTurnTableList = append(CfgTurnTableList, clItem)
		}
	}

	return CfgTurnTableList
}

// 中奖
func GetTurnTableAward(turnTableType int) (int, float64) {
	rateSum := 0
	for _, cfgItem := range G_CfgTurnTableList {
		if cfgItem.Type == turnTableType {
			rateSum += cfgItem.Rate
		}
	}

	if rateSum <= 0 {
		return 0, 0.0
	}

	rand.New(rand.NewSource(time.Now().UnixNano()))
	randValue := rand.Intn(rateSum) + 1

	for _, cfgItem := range G_CfgTurnTableList {
		if cfgItem.Type == turnTableType {
			if cfgItem.Rate < randValue {
				randValue -= cfgItem.Rate
			} else {
				return cfgItem.Id, cfgItem.LuckyPoint
			}
		}
	}

	return 0, 0.0
}
